<?php
	$time_to_expire_session = 30;
	$host = "localhost";
	$port = "5432";
	$dbname = "postgres"; 
	$user = "postgres";
	$password = "123456"; 
	$bdcon3 = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
	
	function geraNovaSessao(){
		global $_SESSION;
		session_destroy();
		session_start();
		session_regenerate_id();
		$session_id = session_id();
		
		$arr = pg_fetch_array(pg_query("INSERT INTO session (php_session_id, start_server_time) VALUES 
										(	'$session_id', 
											(SELECT TIMESTAMP WITH TIME ZONE 'epoch' + ".time()." * INTERVAL '1 second')
										) RETURNING id;"));
		$_SESSION['id_sessao'] = $arr[0];
	}
	
	function checkExpireSession(){
		global $_SESSION;
		global $time_to_expire_session;
		$result = pg_fetch_array(pg_query("SELECT EXTRACT(EPOCH FROM (now()-last_time_update))::int FROM session WHERE id = {$_SESSION['id_sessao']}"));
	
		if($result[0] < $time_to_expire_session)
			pg_query("UPDATE session set last_time_update = now() WHERE id = {$_SESSION['id_sessao']}");
		else
			geraNovaSessao();
	}
	
	session_start();
	$session_id = session_id();

	if(pg_num_rows(pg_query("SELECT * FROM session WHERE php_session_id='$session_id' and end_of_session IS NOT NULL;")) != 0 
					|| !isset($_SESSION['id_sessao']) 
					|| pg_num_rows(pg_query("SELECT * FROM session WHERE php_session_id='$session_id';")) == 0)
		geraNovaSessao();
	else
		checkExpireSession();
	
	$dados = json_decode ( $_POST['dados'] , true );
	
	$query = "";
	for($i = 0; $i < count($dados); $i++ ){
		if($dados[$i]['id'] == 4)
			$query .= "UPDATE session SET 
								url='{$dados[$i]['value']}'
							WHERE id = {$_SESSION['id_sessao']};";
							
		if($dados[$i]['id'] == 3)
			$query .= "UPDATE session SET 
								end_of_session=(SELECT TIMESTAMP WITH TIME ZONE 'epoch' + {$dados[$i]['time']} * INTERVAL '1 millisecond')
							WHERE id = {$_SESSION['id_sessao']};";
							
		if($dados[$i]['id'] == 0)
			$query .= "UPDATE session SET 
								start_of_session=(SELECT TIMESTAMP WITH TIME ZONE 'epoch' + {$dados[$i]['time']} * INTERVAL '1 millisecond')
							WHERE id = {$_SESSION['id_sessao']};";
		
		$query .= "INSERT INTO event (type_event_id, session_id, value, time_event) VALUES ({$dados[$i]['id']}, {$_SESSION['id_sessao']}, '{$dados[$i]['value']}', (SELECT TIMESTAMP WITH TIME ZONE 'epoch' + {$dados[$i]['time']} * INTERVAL '1 millisecond'));";
	}
	pg_query($query);
	
	//header("HTTP/1.0 204 No Response");
?>